package com.xit.cloud.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xit.cloud.entity.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author malguy-wang sir
 * @create ---
 */
@Service("userDetailsService") //当前对象注入容器时的名称
public class myUserDetailsService implements UserDetailsService {
    @Autowired
    private com.xit.cloud.mappers.userMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名来查询数据库
        QueryWrapper<user> wrapper = new QueryWrapper<>();
        wrapper.eq("username",username);
        user user = userMapper.selectOne(wrapper);
        //判断是否存在
        if(user==null) throw new UsernameNotFoundException("用户名不存在");//抛出异常
        //权限集合
        String authorityString = user.getAuthorityString();
        List<GrantedAuthority> auths = AuthorityUtils.commaSeparatedStringToAuthorityList(authorityString);
        //返回一个认证成功的用户信息
        return new User(user.getUsername(),new BCryptPasswordEncoder().encode(user.getPassword()),auths);
    }
}
